<template>
  <view>
    <view class="mini-box" v-if="isNewUser && withdrawalTarget > 0">
      <image class="mini-img" :src="`${BestImgUrl}/Group 34412.png`" @click="showPopup"></image>
      <view class="remaining-amount">
        <text>还差{{withdrawalTarget}}元</text>
      </view>
    </view>
    <!-- Popup Overlay -->
    <view class="popup-overlay" v-if="isPopupVisible" >
      <!-- Popup Content -->
      <view class="popup-content" :class="{ 'shrink-animation': isShrinking, 'tilt-shake-animation': !isShrinking }"
        @click.stop>
        <view class="items-box">
          <view class="items" v-for="item in itemList" :key="item">
            <view class="left-num"><span style="font-size: 60rpx;">{{ Number(item.amount) }}</span><span>元</span></view>
            <view class="right-text">{{ item.title + item.describe }}</view>
          </view>
        </view>
        <!-- 领取按钮 -->
        <view class="claiming-btn" @click="openlogin">{{rewardsText}}</view>
      </view>

      <!-- 删除按钮 -->
      <view class="delet-icon" @click="startCloseAnimation()">
        <u-icon name="close-circle" color="#FFFFFF" size="50"></u-icon>
        <!--<image src="http://yyadmin.laimeitong.com/images/delet.png"></image>-->
      </view>
    </view>
    <!-- 错误提示 -->
    <animationError ref="animationError" :showText="errortext"></animationError>

  </view>
</template>

<script>
const app = getApp();
import store from '@/public/store.js'
import newUserRewardApi from '@/api/newUserReward.js'
import animationError from '@/components/effect-component/animation-error.vue'
export default {
  name: "effect-first",
  components: {
    animationError
  },
  data() {
    return {
      isPopupVisible: false, // Controls popup visibility
      isShrinking: false, // Controls shrinking animation
      BestImgUrl: app.globalData.imgurl,
      withdrawalTarget: store.state.withdrawalTarget || 10, // 提现标准金额
      currentAmount: 0, // 当前金额
      itemList: [],
      showIcon: false,
      iftoken: false,
      isNewUser: false, // 是否是新人
      errortext:'该活动仅限平台新用户参与!'
    };
  },
  watch: {
    '$store.state.withdrawalTarget': {
      handler(newVal) {
        // console.log('watch', newVal)
        if (newVal !== undefined) {
          this.withdrawalTarget = newVal;
        }
      },
      immediate: true,
      deep: true
    }
  },
  computed: {
    // remainingAmount() {
    //   return this.withdrawalTarget - this.currentAmount;
    // },
    rewardsText() {
      this.iftoken = uni.getStorageSync('token')
      return this.iftoken ? '立即领取' : '立即登陆领取';
    }
  },
  mounted() {
    // let iftoken = uni.getStorageSync('token')
    // if(iftoken){
    //   this.initFirst('loginSuccess')
    //   return
    // }

    this.initFirst()
  },
  methods: {
    // 初始化弹出框
    initFirst(flag) {
      let iftoken = uni.getStorageSync('token')
      //获取省份判断是否显示旧版提现入口
      let CityName = uni.getStorageSync('CityName')
      let Province = uni.getStorageSync('Province')
      const submitData = {
        province: Province,
        city: CityName
      }
      const that = this
      //调用此方法不显示弹窗
      const getErrorModel = function() {
        if (flag === 'loginSuccess') {
          that.$refs.animationError.showUp()
        }
        that.isNewUser = false

        //控制默认是否弹窗动画
        that.isPopupVisible = false
      }
      // console.log('this.',this.$refs)
      // if (flag === 'loginSuccess') return
      newUserRewardApi.getNewUserReward(submitData).then(res => {
        //console.log('newUserRewardApi.getNewUserReward', res.data)
        const data = res.data
        const {code} = data
        let result = data.result
        // if (flag === 'loginSuccess') {
        //   result = []

        //   getErrorModel()
        // }
        if (code == 200 && result && result.length) {
          this.itemList = result
          let newUserflag = false
          result.forEach(item=>{
            if (item.is_receive === 0 || item.is_receive === 1){
              newUserflag = true
            }
          })
          if (newUserflag) {
            this.isNewUser = true
          }
          if (iftoken) {
            newUserRewardApi.getMyReward().then(reponse => {
                const data_tow = reponse.data
                const {result, code} = data_tow
                store.commit('setWithdrawalTarget', result.difference_amount)
                //console.log('newUserflag',newUserflag)
                //判断是否是新用户，如果是新用户，则显示弹窗，否则隐藏弹窗
                if (newUserflag) {
                  this.showPopup()
                } else {
                  getErrorModel() //隐藏弹窗
                }
            })
            return
          }
          this.showPopup()
        } else {
          this.errortext = data.msg
          getErrorModel()
        }
      }).catch(error => {
        this.errortext = error.data.msg
        getErrorModel()
      })
    },
    openFinsh() {
      this.iftoken = uni.getStorageSync('token')
      if (this.iftoken) {
        this.$emit('openFinsh')
      } else {
        this.showPopup()
      }
    },
    // Show popup点击首页浮动领取按钮
    showPopup() {
      this.isPopupVisible = true;
      this.isShrinking = false;
    },
    // 领取新人福利
    openlogin() {
      let iftoken = uni.getStorageSync('token')
      //微信APP登录方式
      let that = this
      // this.startCloseAnimation(()=>{
      //   this.$emit('close');
      // })
      if (!iftoken) {
        // 微信小程序静默登录
        // #ifdef MP-WEIXIN
        wx.getUserProfile({
          desc: '获取用户授权', // 声明获取用户个人信息后的用途
          success: (res) => {
            console.log('用户信息==:', this.userinfo);
            if (res.userInfo){
              this.userinfo = res.userInfo
              // 缓存用户信息
              uni.setStorageSync('userinfo', res.userInfo)
              this.wxminiAppLogon();
            }else {
              uni.showModal({
                title: '警告',
                content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!',
                showCancel: false,
                confirmText: '返回授权',
                success: function (res) {
                  if (res.confirm) {
                    console.log('用户点击了“返回授权”');
                  }
                }
              });
            }
          }
        });
        /* uni.login({
          provider: 'weixin',
          success: (loginRes) => {
            that.$api.wxminiappLogon({
              code: loginRes.code,
              avatar: store.state.baseUrl + '/public/uploads/h5/me/Group-33475.png', //	是	string	用户头像
              nickname: '领食惠探店用户',
              username: '',
              appid: uni.getStorageSync('miniProgramAppId')
            }).then(res => {
              //console.log('微信小程序登录', res)
              uni.setStorageSync('token', res.data.result.token)
              this.iftoken = uni.getStorageSync('token')
              uni.showToast({
                title: '登录成功',
                duration: 500
              });
              setTimeout(() => {
                that.$api.GetuserInfo({
                }).then(res => {
                  uni.setStorageSync('userinfo', res.data.result)
                  this.$emit('loginSuccess',);
                  this.initFirst('loginSuccess');
                }).catch(err => {
                })
              }, 500);
            }).catch(err => {})
          }
        }); */
        // #endif
      } else {
        this.startCloseAnimation(()=>{
          this.$emit('close');
        })
      }
    },
    // 获取用户信息
    wxminiAppLogon() {
      let that = this
      uni.login({
          provider: 'weixin',
          success: (loginRes) => {
            that.$api.wxminiappLogon({
              code: loginRes.code, //	是	string	登录授权code
              avatar: that.userinfo ? that.userinfo.avatarUrl : that.BestImgUrl + '/home_logo.png', //	是	string	用户头像
              nickname: that.userinfo ? that.userinfo.nickName : '领食惠探店用户', //	是	string	用户昵称
              username: that.phoneNum, //绑定的手机号，手机号一键登录提示未注册时，
              appid: uni.getStorageSync('miniProgramAppId')
            }).then(res => {
              //console.log('微信小程序登录', res)
              uni.setStorageSync('token', res.data.result.token)
              this.iftoken = uni.getStorageSync('token')
              uni.showToast({
                title: '登录成功',
                duration: 500
              });
              setTimeout(() => {
                that.$api.GetuserInfo({
                }).then(res => {
                  uni.setStorageSync('userinfo', res.data.result)
                  this.$emit('loginSuccess',);
                  this.initFirst('loginSuccess');
                }).catch(err => {
                })
              }, 500);
            }).catch(err => {})
          }
      });
    },
    // Start closing animation and shrink the popup
    startCloseAnimation(fn) {
      this.isShrinking = true;

      // Wait for the animation to complete before fully hiding the popup
      setTimeout(() => {
        this.isPopupVisible = false;
        this.isShrinking = false;
        if (fn) {
          fn()
        }
        this.updateCurrentAmount();
      }, 1000); // Match the animation duration in CSS
    },
    // 更新当前金额
    updateCurrentAmount() {
      // 触发父组件更新
      // this.$emit('updateCurrentAmount');
    },
  },
};
</script>

<style scoped>
@import "./css/index-xg.css";

.mini-box {
  position: fixed;
  right: 20rpx;
  bottom: 250rpx;
  z-index: 99;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.mini-img {
  width: 120rpx;
  height: 120rpx;
}

.remaining-amount {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  color: #fff;
  font-size: 20rpx;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  white-space: nowrap;
}

</style>
